package com.situ.onlinebookstore.back.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.situ.onlinebookstore.back.service.CategoryService;
import com.situ.onlinebookstore.common.entity.Category;
import com.situ.onlinebookstore.common.mapper.CategoryMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class CategoryServiceImpl implements CategoryService {
    private final CategoryMapper categoryMapper;

    @Override
    public int add(Category category) throws Exception {
        //分类名不能重复
        Category sCategory = categoryMapper.selectByName(category.getName());
        if (sCategory != null) {
            throw new Exception("分类名已存在！");
        }
        //插入数据库

        return categoryMapper.insert(category);
    }

    @Override
    public int edit(Category category) throws Exception {
        //判断ID
        Category sCategory = categoryMapper.selectById(category.getId());
        if (sCategory == null) {
            throw new Exception("分类ID不存在");
        }
        //分类名不能重复
        Category sCategory1 = categoryMapper.selectByName(category.getName());
        if (sCategory1 != null && !category.getId().equals(sCategory1.getId())) {
            throw new Exception("分类名已存在！");
        }

        //状态不能与原来的相同
        if (category.getStatus() != null) {
            if (category.getStatus().equals(sCategory.getStatus())) {
                throw new Exception("状态不能重复修改！");
            }
        }
        //更新到数据库
        return categoryMapper.update(category);
    }

    @Override
    public List search(Category category) {
        return categoryMapper.select(category);
    }

    @Override
    public PageInfo searchByPage(Integer page, Integer limit, Category category) {
        PageHelper.startPage(page, limit);
        List list = categoryMapper.select(category);
        return new PageInfo(list);
    }
}
